package com.lrkj.property.service.impl;

import com.lrkj.common.annotation.DataScope;
import com.lrkj.common.constant.OrgConstants;
import com.lrkj.common.constant.PropertyConstants;
import com.lrkj.common.core.domain.entity.OrgTree;
import com.lrkj.common.exception.BaseException;
import com.lrkj.common.utils.DateUtils;
import com.lrkj.common.utils.SecurityUtils;
import com.lrkj.common.utils.StringUtils;
import com.lrkj.common.utils.uuid.IdUtils;
import com.lrkj.framework.utils.NumberUtils;
import com.lrkj.payfee.service.IRoomNormService;
import com.lrkj.property.domain.Community;
import com.lrkj.property.domain.Floor;
import com.lrkj.property.domain.Room;
import com.lrkj.property.domain.Unit;
import com.lrkj.property.mapper.RoomMapper;
import com.lrkj.property.service.ICommunityService;
import com.lrkj.property.service.IFloorService;
import com.lrkj.property.service.IRoomService;
import com.lrkj.property.service.IUnitService;
import com.lrkj.property.vo.BatchRoomVo;
import com.lrkj.property.vo.RoomVo;
import com.lrkj.system.service.IOrgTreeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 房屋管理Service业务层处理
 *
 * @author yajun_ren
 * @date 2021-07-22
 */
@Service
public class RoomServiceImpl implements IRoomService {
    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private ICommunityService communityService;


    @Autowired
    private IOrgTreeService orgTreeService;

    @Autowired
    private IFloorService iFloorService;

    @Autowired
    private IUnitService unitService;

    @Autowired
    private IRoomNormService roomNormService;

    /**
     * 查询房屋管理
     *
     * @param id 房屋管理ID
     * @return 房屋管理
     */
    @Override
    public Room selectRoomById(String id) {
        return roomMapper.selectRoomById(id);
    }

    /**
     * 查询房屋管理列表
     *
     * @param room 房屋管理
     * @return 房屋管理
     */
    @Override
    @DataScope(deptAlias = "t")
    public List<Room> selectRoomList(Room room) {
        return roomMapper.selectRoomList(room);
    }

    /**
     * 新增房屋管理
     *
     * @param room 房屋管理
     * @return 结果
     */
    @Override
    public int insertRoom(Room room) {
        room.setId(IdUtils.simpleUUID());
        room.setCreateBy(SecurityUtils.getUsername());
        room.setCreateTime(DateUtils.getNowDate());
        this.setUnitInfo(room);
        return roomMapper.insertRoom(room);
    }

    /**
     * 修改房屋管理
     *
     * @param room 房屋管理
     * @return 结果
     */
    @Override
    public int updateRoom(Room room) {
        this.setUnitInfo(room);
        room.setUpdateBy(SecurityUtils.getUsername());
        room.setUpdateTime(DateUtils.getNowDate());
        return roomMapper.updateRoom(room);
    }

    /**
     * 批量删除房屋管理
     *
     * @param ids 需要删除的房屋管理ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteRoomByIds(String[] ids) {
        for (int i = 0; i < ids.length; i++) {
            int row = roomNormService.selRoomNormByRoomId(ids[i]);
            if (row>0){
                Room room = roomMapper.selectRoomById(ids[i]);
                throw new BaseException(String.format("房间名:%s已绑定收费标准不可删除", room.getRoomName()));
            }
        }
        orgTreeService.deleteOrgTreeByIds(ids);
        return roomMapper.deleteRoomByIds(ids);
    }

    /**
     * 删除房屋管理信息
     *
     * @param id 房屋管理ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteRoomById(String id) {

        int row = roomNormService.selRoomNormByRoomId(id);
        if (row>0){
            Room room = roomMapper.selectRoomById(id);
            throw new BaseException(String.format("房间名:%s已绑定收费标准不可删除", room.getRoomName()));
        }
        orgTreeService.deleteOrgTreeById(id);
        return roomMapper.deleteRoomById(id);
    }

    @Override
    public int doSaveList(List<Room> saveBeans) {
        return roomMapper.doSaveList(saveBeans);
    }

    @Override
    public int UpdateOwnerId(String ownerId, String id) {
        return roomMapper.UpdateOwnerId(ownerId, id);
    }

    @Override
    public int selectCount(Room room) {
        return roomMapper.selectCount(room);
    }

    @Override
    public int maxRoomNum(String floorId) {
        return roomMapper.maxRoomNum(floorId);
    }

    /**
     * 新增楼层数量
     **/
    @Override
    @Transactional
    public int addLayerNum(RoomVo roomVo) {
        this.checkParams(roomVo);
        Unit unit = unitService.selectUnitById(roomVo.getUnitId());
        Floor floor = iFloorService.selectFloorById(unit.getFloorId());
        // 根据楼栋生成 房屋编号
        AtomicInteger floorRoomNum = new AtomicInteger(0);
        //按照楼统一编排
        if (floor.getRoomRule().equals(PropertyConstants.room_rule_10)) {
            floorRoomNum.set(roomMapper.maxRoomNum(unit.getFloorId()));
        }
        //获取单元下最大楼层数
        AtomicInteger layerNum = new AtomicInteger(roomMapper.maxUnitLayerNum(unit.getId()));
        Community community = communityService.selectCommunityById(unit.getCommunityId());
        List<Room> savaRooms = new ArrayList<>();
        for (Integer i = 0; i < roomVo.getLayerNum(); i++) {
            //楼层加一
            layerNum.incrementAndGet();
            for (int j = 0; j < roomVo.getRoomNum(); j++) {
                int roomNum = j + 1;


                Room bean = new Room();
                bean.setId(IdUtils.simpleUUID());
                bean.setUnitId(unit.getId());
                bean.setFloorId(unit.getFloorId());
                bean.setCommunityId(community.getId());
                bean.setDeptId(community.getDeptId());
                String houseNum = "";
                //门牌号生成规则
                if (StringUtils.isNotEmpty(floor.getRoomRule())) {
                    if (floor.getRoomRule().equals(PropertyConstants.room_rule_10)) {
                        floorRoomNum.incrementAndGet();
                        //按照楼统一编排
                        houseNum = NumberUtils.frontCompWithZore(floorRoomNum.get(), 3);
                        bean.setRoomOrder(floorRoomNum.get());
                    } else if (floor.getRoomRule().equals(PropertyConstants.room_rule_20)) {
                        //按照楼层和房间号编排
                        houseNum = NumberUtils.frontCompWithZore(layerNum.get(), 2) + NumberUtils.frontCompWithZore(roomNum, 2);
                        bean.setRoomOrder(roomNum);
                    }
                }

                bean.setLayerNum(layerNum + "");
                bean.setRoomNum(houseNum);
                bean.setDataSourceId("系统创建");
                bean.setStatusCd("0");
                bean.setCreateTime(DateUtils.getNowDate());
                bean.setCreateBy(SecurityUtils.getUsername());
                bean.setAncestors(unit.getAncestors() + "," + unit.getId());
                bean.setRoomName(floor.getFloorNum() + "-" + unit.getUnitNum() + "-" + houseNum);
                String cityName = "";
                if (StringUtils.isNotEmpty(community.getCityName())) {
                    String[] split = community.getCityName().split("/");
                    for (String s : split) {
                        cityName += s;
                    }
                }
                bean.setAddress(cityName + community.getCommunityName() + floor.getFloorName() + unit.getUnitName() + bean.getRoomNum());
                orgTreeService.insertOrgTree(bean.getId(), bean.getRoomNum(), bean.getUnitId(), OrgConstants.room, bean.getAncestors(), Integer.valueOf(bean.getRoomNum()));
                savaRooms.add(bean);
            }
        }
        roomMapper.doSaveList(savaRooms);
        return 1;
    }

    /**
     * 新增房间数量
     **/
    @Override
    @Transactional
    public int addRoomNum(RoomVo roomVo) {
        this.checkParams(roomVo);
        Unit unit = unitService.selectUnitById(roomVo.getUnitId());
        Floor floor = iFloorService.selectFloorById(unit.getFloorId());
        // 根据楼栋生成 房屋编号
        AtomicInteger floorRoomNum = new AtomicInteger(0);
        //按照楼统一编排
        if (floor.getRoomRule().equals(PropertyConstants.room_rule_10)) {
            floorRoomNum.set(roomMapper.maxRoomNum(unit.getFloorId()));
        } else {
            floorRoomNum.set(roomMapper.maxUnitLayerRoomNum(unit.getId(), roomVo.getLayerNum()));
        }
        Community community = communityService.selectCommunityById(unit.getCommunityId());
        List<Room> savaRooms = new ArrayList<>();
        for (int j = 0; j < roomVo.getRoomNum(); j++) {
            floorRoomNum.incrementAndGet();
            Room bean = new Room();
            bean.setId(IdUtils.simpleUUID());
            bean.setUnitId(unit.getId());
            bean.setFloorId(unit.getFloorId());
            bean.setCommunityId(community.getId());
            bean.setDeptId(community.getDeptId());
            String houseNum = "";
            //门牌号生成规则
            if (StringUtils.isNotEmpty(floor.getRoomRule())) {
                if (floor.getRoomRule().equals(PropertyConstants.room_rule_10)) {
                    //按照楼统一编排
                    houseNum = NumberUtils.frontCompWithZore(floorRoomNum.get(), 3);
                } else if (floor.getRoomRule().equals(PropertyConstants.room_rule_20)) {
                    //按照楼层和房间号编排
                    houseNum = NumberUtils.frontCompWithZore(roomVo.getLayerNum(), 2) + NumberUtils.frontCompWithZore(floorRoomNum.get(), 2);
                }
            }

            bean.setRoomOrder(floorRoomNum.get());
            bean.setLayerNum(roomVo.getLayerNum() + "");
            bean.setRoomNum(houseNum);
            bean.setDataSourceId("系统创建");
            bean.setStatusCd(PropertyConstants.housing_status_10001);
            bean.setCreateTime(DateUtils.getNowDate());
            bean.setCreateBy(SecurityUtils.getUsername());
            bean.setAncestors(unit.getAncestors() + "," + unit.getId());


            bean.setRoomName(floor.getFloorName() + "-" + unit.getUnitName() + "-" + houseNum);
            String cityName = "";
            if (StringUtils.isNotEmpty(community.getCityName())) {
                String[] split = community.getCityName().split("/");
                for (String s : split) {
                    cityName += s;
                }
            }
            bean.setAddress(cityName + community.getCommunityName() + floor.getFloorName() + unit.getUnitName() + bean.getRoomNum());
            orgTreeService.insertOrgTree(bean.getId(), bean.getRoomNum(), bean.getUnitId(), OrgConstants.room, bean.getAncestors(), Integer.valueOf(bean.getRoomNum()));
            savaRooms.add(bean);
        }
        roomMapper.doSaveList(savaRooms);
        return 1;
    }

    @Override
    public Map<String, Object> censusRoomInfo(Room room) {
        return roomMapper.censusRoomInfo(room);
    }

    @Override
    public int batchUpdateRoom(BatchRoomVo batchRoomVo) {
        if (batchRoomVo.getUpdateForms().size() > 0) {
            Map<String, Object> bean = new HashMap<>();
            StringBuffer valuesSql = new StringBuffer("set ");
            batchRoomVo.getUpdateForms().stream().forEach(x -> {
                valuesSql.append(x.getKey() + "=");
                valuesSql.append("#{bean.");
                valuesSql.append(x.getKey());
                valuesSql.append(",jdbcType=");
                valuesSql.append(x.getDataType());
                valuesSql.append("}");
                valuesSql.append(",");
                bean.put(x.getKey(), x.getUpdateVal());
            });
            valuesSql.deleteCharAt(valuesSql.length() - 1);
            Map<String, Object> params = new HashMap();
            params.put("tableName", "tm_room");
            params.put("sql", valuesSql);
            params.put("communityId", batchRoomVo.getCommunityId());
            params.put("floorId", batchRoomVo.getFloorId());
            params.put("unitId", batchRoomVo.getUnitId());
            params.put("roomId", batchRoomVo.getRoomId());
            params.put("bean", bean);
            roomMapper.trendUpdateRoom(params);
        }
        return 1;
    }


    private void checkParams(RoomVo roomVo) {
        if (roomVo.getLayerNum() < 1) {
            throw new BaseException("单元层数必须大于0");
        }
        if (roomVo.getRoomNum() < 1) {
            throw new BaseException("单元户数必须大于0");
        }
    }

    private void setUnitInfo(Room bean) {
        Unit parentBean = unitService.selectUnitById(bean.getUnitId());
        bean.setAncestors(parentBean.getAncestors() + "," + bean.getUnitId());
        bean.setDeptId(parentBean.getDeptId());
        bean.setRoomName(parentBean.getFloorNum() + "-" + parentBean.getUnitNum() + "-" + bean.getRoomNum());
        String cityName = "";
        if (StringUtils.isNotEmpty(parentBean.getCityName())) {
            String[] split = parentBean.getCityName().split("/");
            for (String s : split) {
                cityName += s;
            }
        }
        bean.setAddress(cityName + parentBean.getCommunityName() + parentBean.getFloorName() + parentBean.getUnitName() + bean.getRoomNum());
        OrgTree orgTree = new OrgTree();
        orgTree.setId(bean.getId());
        orgTree.setName(bean.getRoomNum());
        orgTree.setParentId(bean.getUnitId());
        orgTree.setModelType(OrgConstants.room);
        orgTree.setAncestors(bean.getAncestors());
        orgTree.setOrderNum(Integer.valueOf(bean.getRoomNum()));
        orgTreeService.insertOrgTree(orgTree);
    }

    /**
     * 批量新增房屋管理信息
     *
     * @param rooms 房屋管理对象
     */
    public int batchAddData(List<Room> rooms) {
        return roomMapper.batchAddData(rooms);
    }
}
